<template>
  <div class="app-container">
    <!-- 字典列表 -->
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="10" :lg="24" :xl="24" style="margin-bottom: 10px">
        <el-card class="box-card">
          <!--工具栏-->
          <div class="head-container">
            <!-- 搜索 -->
            <el-input v-model="listQuery.searchText" clearable size="small" placeholder="输入名称搜索" style="width: 200px;"
                      class="filter-item" @keyup.enter.native="getTablePage()"/>
            <span>
                <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="getTablePage()">搜索</el-button>
                <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="reset()">重置</el-button>
             </span>

            <div class="crud-opts">
                <span class="crud-opts-left">
                <!--左侧插槽-->
                <slot name="left"/>
                <el-button
                  v-permission="permission.add"
                  class="filter-item"
                  size="mini"
                  type="primary"
                  icon="el-icon-plus"
                  @click="openDialogTableForm(false)"
                >
                    新增
                </el-button>
                <el-button
                  v-permission="permission.del"
                  slot="reference"
                  class="filter-item"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteTableData"
                >
                    删除
                </el-button>
                </span>
            </div>
          </div>
          <!--表单渲染-->
          <!--表格渲染-->
          <el-table
            ref="table"
            v-loading="listLoading"
            :data="list"
            highlight-current-row
            class="table-height"
          >
            <el-table-column type="selection" width="55"/>
            <el-table-column :show-overflow-tooltip="true" prop="logoUrl" label="logo">
              <template slot-scope="scope" v-if="scope.row.logoUrl != null">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.logoUrl"
                  :preview-src-list="[scope.row.logoUrl]"
                  fit="fill"
                  lazy></el-image>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="simplename" label="简称"/>
            <el-table-column :show-overflow-tooltip="true" prop="fullname" label="全称"/>
            <el-table-column :show-overflow-tooltip="true" prop="typeName" label="类型"/>
            <el-table-column :show-overflow-tooltip="true" prop="regionName" label="区域"/>
            <el-table-column label="操作" width="160px" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button v-permission="permission.edit" style="margin-left: 10px" type="primary" icon="el-icon-edit"
                           size="mini" @click="openDialogTableForm(true,scope.row)">修改
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            style="margin-top: 8px;"
            layout="total, prev, pager, next"
            v-show="total>0"
            :page-size="listQuery.pageSize"
            :total="total"
            prev-text="上一页"
            next-text="下一页"
            @current-change="paginationChange"
          >
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹出框新增table -->
    <el-dialog title="公司信息" :visible.sync="dialogTableFormVisible" width="900px">
      <el-form
        ref="tableForm"
        :model="tableForm"
        :rules="rules"
        label-position="right"
        style="width: 740px; margin-left:20px; margin-right: 0px;"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="简称" prop="simplename" label-width="120px">
              <el-input v-model="tableForm.simplename" maxlength="45" style="width:220px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="全称" prop="fullname" label-width="120px">
              <el-input v-model="tableForm.fullname" maxlength="255" style="width:220px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="type" label-width="120px">
              <el-select v-model="tableForm.companyType" placeholder="请选择">
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域" prop="region" label-width="120px">
              <el-select v-model="tableForm.companyRegion" placeholder="请选择">
                <el-option
                  v-for="item in regions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="logo" label-width="120px">
              <el-upload
                class="avatar-uploader"
                action
                accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
                :show-file-list="false"
                :http-request="httpRequest">
                <img v-if="tableForm.logoUrl" :src="tableForm.logoUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="应用" prop="applicationIds" label-width="120px">
              <el-select
                class="forrm-select"
                v-model="tableForm.applicationIds"
                multiple
                placeholder="请选择应用">
                <el-option
                  v-for="item in applications"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveTable">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {uploadFile} from '@/api/file'
  import {getByCode} from '@/api/system/dict'
  import {add, edit, del, getTablePage} from '@/api/system/company'
  import {getApplicationList, getApplicationByCompanyId} from '@/api/system/application'
  import {getUserInfo} from '@/utils/session'

  // 定义table 的表单
  const tableForm = {
    id: '',
    simplename: '',
    fullname: '',
    companyType: '',
    companyRegion: '',
    logo: '',
    logoUrl: '',
    applicationIds: []
  }
  export default {
    data() {
      return {
        permission: {
          add: ['admin', 'company:add'],
          edit: ['admin', 'company:edit'],
          del: ['admin', 'company:del']
        },
        applications: [],
        module: 'company',
        types: [],
        regions: [],
        isEdit: false,
        tableForm: tableForm,
        dialogTableFormVisible: false, // 弹出的新增修改表单窗口
        listLoading: false,
        searchText: '',
        total: 0,
        list: null,
        listQuery: {
          pageNo: 0,
          pageSize: 7,
          searchText: '',
        },
        rules: {
          simplename: [
            {required: true, trigger: 'blur', message: '简称不能为空'},
            {max: 45, message: '简称最大45字符', trigger: 'blur'}
          ],
          fullname: [{max: 255, message: '全称最大255字符', trigger: 'blur'}],
          applicationIds: [
            {
              required: true, trigger: 'blur', message: '应用不能为空'
            }
          ]
        }
      };
    },
    created() {
      this.getTablePage();
    },
    methods: {
      getApplications(isEdit, row) {
        getApplicationList().then(res => {
          this.applications = res.data.content

          if (isEdit) {
            //修改时回显数据
            getApplicationByCompanyId(row.id).then(res => {
              var companyApplicationList = res.data;
              if (companyApplicationList != null && companyApplicationList.length > 0) {
                //后端取已经绑定的应用id
                var companyApplicationIds = [];
                for (var i in companyApplicationList) {
                  companyApplicationIds.push(companyApplicationList[i].id);
                }

                this.$set(this.tableForm, 'applicationIds', companyApplicationIds);
              }
            })
          }
        })
      },
      httpRequest(param) {
        const user = getUserInfo()
        let fd = new FormData();
        fd.append('file', param.file);
        fd.append('part', 'one');
        fd.append('module', this.module);
        fd.append('createrId', user.id);
        fd.append('createrComId', user.companyId);
        uploadFile(fd).then(response => {
          this.tableForm.logo = response.data.id;
          this.tableForm.logoUrl = response.data.url;
        })
      },
      paginationChange(index) {
        this.listQuery.pageNo = index - 1
        this.getTablePage()
      },
      getTablePage() {
        this.listLoading = true
        getTablePage(this.listQuery).then(res => {
          this.list = res.data.content
          this.total = res.data.totalElements
          res.data.content.forEach((item, index) => {
            item.listIndex = index
          });
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        })
      },
      reset() {
        //this.listQuery.pageNo=0;
        this.listQuery.searchText = null;
        this.getTablePage();
      },
      // 打开tableform窗口
      openDialogTableForm(isEdit, row) {
        this.isEdit = isEdit
        this.loadTypes();
        this.loadRegions();
        this.getApplications(isEdit, row);
        if (isEdit) {
          this.tableForm = row
          this.dialogTableFormVisible = true
        } else {
          this.dialogTableFormVisible = true
          this.tableForm = {
            id: '',
            simplename: '',
            fullname: '',
            companyType: '',
            companyRegion: '',
            logo: '',
            logoUrl: '',
            applicationIds: []
          }
        }
      },
      cancel() {
        this.dialogTableFormVisible = false
      },
      saveTable() {
        this.$refs.tableForm.validate(valid => {
          if (valid) {
            if (this.isEdit) {
              edit(this.tableForm).then(response => {
                this.dialogTableFormVisible = false
                this.$notify({
                  title: '数据表修改成功',
                  type: 'success',
                  duration: 1500
                })
                this.getTablePage()
              }).catch((response) => {
                this.$notify({
                  title: '数据表修改失败',
                  type: 'error',
                  duration: 2500
                })
              })
            } else {
              add(this.tableForm).then(response => {
                this.dialogTableFormVisible = false
                this.$notify({
                  title: '数据表添加成功',
                  type: 'success',
                  duration: 1500
                })
                this.getTablePage()
                this.cancel()
              })
            }
          }
        })
      },
      deleteTableData() {
        let currentSelect = this.$refs.table.selection;
        if (currentSelect.length == 0) {
          this.$notify({
            title: '请选择要删除的数据',
            type: 'error',
            duration: 1500
          })
          return;
        }

        this.$confirm('确认删除' + currentSelect.length + '条数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //点击确定的操作(调用接口)
          var ids = [];
          for (var i in currentSelect) {
            ids.push(currentSelect[i].id);
          }
          del(ids).then(response => {
            this.$notify({
              title: '数据删除成功',
              type: 'success',
              duration: 1500
            })
            this.getTablePage()
            this.cancel()
          })
        }).catch(() => {
          //点取消的提示
        });
      },
      loadTypes() {
        if (this.types.length > 0) {
          return;
        }
        var arr = [];
        getByCode('companyType').then(res => {
          var data = res.data;
          for (var i in data) {
            arr.push({'value': data[i].code, 'label': data[i].name});
          }
        })
        this.types = arr;
      },
      loadRegions() {
        if (this.regions.length > 0) {
          return;
        }
        var arr = [];
        getByCode('companyRegion').then(res => {
          var data = res.data;
          for (var i in data) {
            arr.push({'value': data[i].code, 'label': data[i].name});
          }
        })
        this.regions = arr;
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  /* .table-height {
    width: 100%;
    height: 600px;
  } */
  .forrm-select {
    width: 100%;
  }
</style>
